package org.ccay.excel.importer.service.impl.internal;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.NestedNullException;

import org.ccay.core.log.ILogger;
import org.ccay.core.log.CcayLoggerFactory;
import org.ccay.core.util.StringUtil;

/**
 * 利用BeanUtils实现的VO转换器。
 * 	
 * @author chaowangbang
 * @since Mar 22, 2012
 */
public class VOConverterByBeanUtils extends AbstractVOConverter {
	
	/**
	 * 日志记录器
	 */
	private static final ILogger log = CcayLoggerFactory.getLogger(VOConverterByBeanUtils.class);
	
	/**
	 * Bean Utils
	 */
	private BeanUtilsBean beanUtil;
	
	/**
	 * 构造函数
	 */
	public VOConverterByBeanUtils() {
        // 获取BeanUtilsBean实例
        this.beanUtil = BeanUtilsBean.getInstance();
	}
	/**
	 * @param voClass
	 */
	public VOConverterByBeanUtils(Class<?> voClass) {
		super(voClass);
        
		// 获取BeanUtilsBean实例
        this.beanUtil = BeanUtilsBean.getInstance();
	}

	/* (non-Javadoc)
	 * @see org.ccay.excel.importer.service.impl.internal.AbstractVOConverter#populateObject(java.lang.Object, java.util.Map)
	 */
	@Override
	protected void populateObject(Object instance,
			Map<String, Object> voProperties)  throws ConvertException{
		try {
			beanUtil.populate(instance, voProperties);
		} catch (IllegalAccessException e) {
			throw new ConvertException(e);
		} catch (InvocationTargetException e) {
			throw new ConvertException(e);
		}
	}

	/* (non-Javadoc)
	 * @see org.ccay.excel.importer.service.impl.internal.AbstractVOConverter#getProperties(java.lang.Object, java.lang.String[])
	 */
	@Override
	protected List<Object>  getProperties(Object instance,
			String[] voProperties) {
		List<Object> properties = new ArrayList<Object>(voProperties.length);
		//设置Bean的各属性值
		for (String str : voProperties) {
			if(StringUtil.isNullOrEmpty(str)){
				properties.add(null);
				continue;
			}
			try{
				properties.add(beanUtil.getPropertyUtils().getNestedProperty(instance,str));
			}catch (NestedNullException e) {
				log.warn("Null parent property value for '" + str + "' on bean class '" + instance.getClass() + "'");
				properties.add(null);
			}catch (Exception e) {
				log.warn("Unknown property "+str+" on" + instance.toString(),e);
				properties.add(null);
			}
		}
		return properties;
	}

}
